#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Istio VirtualService 数据库表结构初始化脚本

设计说明:
1. vs_global: 存储VirtualService的全局配置
2. vs_http_routes: 存储HTTP路由规则，每条记录是一条规则

优化建议:
- 将route和delegate分离存储，使用forward_type区分
- 使用JSON字段存储复杂的嵌套结构
- 添加索引优化查询性能
- 添加创建和更新时间戳
"""

import mysql.connector
import json
from typing import Optional, Dict, Any


class VirtualServiceDB:
    def __init__(
        self,
        host: str = "localhost",
        port: int = 3306,
        user: str = "root",
        password: str = "",
        database: str = "virtualservice",
    ):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.conn = None

    def connect(self):
        """连接数据库"""
        try:
            self.conn = mysql.connector.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database,
                charset='utf8mb4',
                autocommit=False,
            )
            return self.conn
        except mysql.connector.Error as e:
            if e.errno == mysql.connector.errorcode.ER_BAD_DB_ERROR:
                # 数据库不存在，先创建数据库
                temp_conn = mysql.connector.connect(
                    host=self.host, port=self.port, user=self.user, password=self.password, charset='utf8mb4'
                )
                cursor = temp_conn.cursor()
                cursor.execute(
                    f"CREATE DATABASE IF NOT EXISTS {self.database} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
                )
                temp_conn.commit()
                cursor.close()
                temp_conn.close()

                # 重新连接到新创建的数据库
                self.conn = mysql.connector.connect(
                    host=self.host,
                    port=self.port,
                    user=self.user,
                    password=self.password,
                    database=self.database,
                    charset='utf8mb4',
                    autocommit=False,
                )
                return self.conn
            else:
                raise e

    def close(self):
        """关闭数据库连接"""
        if self.conn:
            self.conn.close()

    def init_tables(self):
        """初始化数据库表结构"""
        if not self.conn:
            self.connect()

        cursor = self.conn.cursor(dictionary=True)

        # 创建全局配置表
        cursor.execute(
            """
        CREATE TABLE IF NOT EXISTS vs_global (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            namespace VARCHAR(255) NOT NULL DEFAULT 'default',
            gateways TEXT,  -- JSON数组: ["gateway1", "gateway2"]
            hosts TEXT NOT NULL,  -- JSON数组: ["host1.com", "host2.com"]
            protocol VARCHAR(50) DEFAULT 'http',
            df_forward_type VARCHAR(20),  -- 默认路由类型: 'route' 或 'delegate'
            df_forward_detail TEXT,  -- 默认路由详情: JSON格式
            df_forward_timeout VARCHAR(50),  -- 默认路由超时设置
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_name_namespace (name, namespace),
            CHECK (df_forward_type IS NULL OR df_forward_type IN ('route', 'delegate'))
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """
        )

        # 创建HTTP路由规则表
        cursor.execute(
            """
        CREATE TABLE IF NOT EXISTS vs_http_routes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            vs_global_id INT NOT NULL,
            name VARCHAR(255),  -- 路由规则名称(可选)
            priority INT DEFAULT 0,  -- 路由优先级，数字越小优先级越高
            match_rules TEXT,  -- JSON: [{"uri": {"prefix": "/api"}, "authority": {"exact": "api.example.com"}}]
            rewrite_rules TEXT,  -- JSON: {"uri": "/new-path"}
            forward_type VARCHAR(20) NOT NULL,
            forward_detail TEXT NOT NULL,  -- JSON: route时存储destination和headers，delegate时存储name和namespace
            timeout VARCHAR(50),  -- 路由级别的超时设置
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (vs_global_id) REFERENCES vs_global(id) ON DELETE CASCADE,
            CHECK (forward_type IN ('route', 'delegate'))
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """
        )

        # 创建K8S集群关联表
        cursor.execute(
            """
        CREATE TABLE IF NOT EXISTS k8s_cluster (
            id INT AUTO_INCREMENT PRIMARY KEY,
            k8s_name VARCHAR(255) NOT NULL COMMENT 'K8S集群名称',
            vs_id INT NOT NULL COMMENT 'VirtualService ID',
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (vs_id) REFERENCES vs_global(id) ON DELETE CASCADE,
            INDEX idx_k8s_name (k8s_name),
            INDEX idx_vs_id (vs_id),
            UNIQUE KEY unique_k8s_vs (k8s_name, vs_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='K8S集群与VirtualService关联表'
        """
        )

        # 创建索引（MySQL 不支持 IF NOT EXISTS，需要先检查是否存在）
        try:
            cursor.execute("CREATE INDEX idx_vs_global_name_namespace ON vs_global(name, namespace)")
        except mysql.connector.Error as e:
            if e.errno != mysql.connector.errorcode.ER_DUP_KEYNAME:
                raise e

        try:
            cursor.execute("CREATE INDEX idx_vs_http_routes_vs_global_id ON vs_http_routes(vs_global_id)")
        except mysql.connector.Error as e:
            if e.errno != mysql.connector.errorcode.ER_DUP_KEYNAME:
                raise e

        try:
            cursor.execute("CREATE INDEX idx_vs_http_routes_priority ON vs_http_routes(vs_global_id, priority)")
        except mysql.connector.Error as e:
            if e.errno != mysql.connector.errorcode.ER_DUP_KEYNAME:
                raise e

        self.conn.commit()
        
        # 验证表是否创建成功
        cursor.execute("SHOW TABLES")
        table_results = cursor.fetchall()
        # 获取表名，处理字典格式的结果
        if table_results:
            # 获取第一个键名（通常是 'Tables_in_数据库名'）
            table_key = list(table_results[0].keys())[0]
            tables = [table[table_key] for table in table_results]
        else:
            tables = []
            
        expected_tables = ['vs_global', 'vs_http_routes', 'k8s_cluster']
        
        missing_tables = [table for table in expected_tables if table not in tables]
        if missing_tables:
            raise Exception(f"以下表创建失败: {missing_tables}")
        
        print("数据库表结构初始化完成！")
        print(f"已创建的表: {', '.join(tables)}")

    def insert_sample_data(self):
        """插入示例数据"""
        cursor = self.conn.cursor(dictionary=True)

        # 插入全局配置示例
        cursor.execute(
            """
        INSERT INTO vs_global (name, namespace, gateways, hosts, protocol, df_forward_type, df_forward_detail, df_forward_timeout)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
        ON DUPLICATE KEY UPDATE
            gateways = VALUES(gateways),
            hosts = VALUES(hosts),
            protocol = VALUES(protocol),
            df_forward_type = VALUES(df_forward_type),
            df_forward_detail = VALUES(df_forward_detail),
            df_forward_timeout = VALUES(df_forward_timeout)
        """,
            (
                "example-vs",
                "default",
                json.dumps(["istio-system/gateway"]),
                json.dumps(["example.com", "api.example.com"]),
                "http",
                "route",
                json.dumps([{"destination": {"host": "default-service", "port": {"number": 8080}}}]),
                "20s",
            ),
        )

        # 获取插入或更新的记录ID
        cursor.execute("SELECT id FROM vs_global WHERE name = %s AND namespace = %s", ("example-vs", "default"))
        vs_global_id = cursor.fetchone()['id']

        # 插入路由规则示例
        route_examples = [
            {
                "name": "api-route",
                "priority": 1,
                "match_rules": json.dumps([{"uri": {"prefix": "/api"}, "authority": {"exact": "api.example.com"}}]),
                "rewrite_rules": json.dumps({"uri": "/v1"}),
                "forward_type": "route",
                "forward_detail": json.dumps(
                    [
                        {
                            "destination": {"host": "api-service", "port": {"number": 8080}},
                            "headers": {"request": {"set": {"X-Forwarded-Proto": "https"}}},
                        }
                    ]
                ),
                "timeout": "10s",
            },
            {
                "name": "delegate-route",
                "priority": 2,
                "match_rules": json.dumps([{"uri": {"prefix": "/orders"}}]),
                "rewrite_rules": None,
                "forward_type": "delegate",
                "forward_detail": json.dumps({"name": "service-orders-service", "namespace": "sos"}),
                "timeout": None,
            },
        ]

        for route in route_examples:
            cursor.execute(
                """
            INSERT INTO vs_http_routes 
            (vs_global_id, name, priority, match_rules, rewrite_rules, forward_type, forward_detail, timeout)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            """,
                (
                    vs_global_id,
                    route["name"],
                    route["priority"],
                    route["match_rules"],
                    route["rewrite_rules"],
                    route["forward_type"],
                    route["forward_detail"],
                    route["timeout"],
                ),
            )

        # 插入K8S集群关联示例数据
        k8s_cluster_examples = [
            {"k8s_name": "K8S1", "vs_id": vs_global_id},
            {"k8s_name": "K8S2", "vs_id": vs_global_id},
        ]

        # 先插入另一个VS示例用于演示多集群关联
        cursor.execute(
            """
        INSERT INTO vs_global (name, namespace, gateways, hosts, protocol, df_forward_type, df_forward_detail, df_forward_timeout)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
        ON DUPLICATE KEY UPDATE
            gateways = VALUES(gateways),
            hosts = VALUES(hosts),
            protocol = VALUES(protocol),
            df_forward_type = VALUES(df_forward_type),
            df_forward_detail = VALUES(df_forward_detail),
            df_forward_timeout = VALUES(df_forward_timeout)
        """,
            (
                "test-vs",
                "default",
                json.dumps(["istio-system/gateway"]),
                json.dumps(["test.com"]),
                "http",
                "route",
                json.dumps([{"destination": {"host": "test-service", "port": {"number": 8080}}}]),
                "30s",
            ),
        )

        # 获取第二个VS的ID
        cursor.execute("SELECT id FROM vs_global WHERE name = %s AND namespace = %s", ("test-vs", "default"))
        test_vs_id = cursor.fetchone()['id']

        # 添加更多K8S集群关联示例
        k8s_cluster_examples.extend([
            {"k8s_name": "K8S1", "vs_id": test_vs_id},
            {"k8s_name": "K8S2", "vs_id": test_vs_id},
        ])

        for k8s_cluster in k8s_cluster_examples:
            cursor.execute(
                """
            INSERT INTO k8s_cluster (k8s_name, vs_id)
            VALUES (%s, %s)
            ON DUPLICATE KEY UPDATE
                updated_at = CURRENT_TIMESTAMP
            """,
                (k8s_cluster["k8s_name"], k8s_cluster["vs_id"]),
            )

        self.conn.commit()
        print("示例数据插入完成！")
        print("K8S集群关联数据插入完成！")

    def reorder_route_priorities(self, vs_global_id: int):
        """重新整理路由规则的优先级，确保连续性"""
        cursor = self.conn.cursor(dictionary=True)

        # 获取所有路由规则，按当前优先级排序
        cursor.execute(
            """
        SELECT id FROM vs_http_routes WHERE vs_global_id = %s ORDER BY priority ASC, id ASC
        """,
            (vs_global_id,),
        )

        routes = cursor.fetchall()

        # 重新分配优先级
        for index, route in enumerate(routes):
            new_priority = (index + 1) * 10  # 使用10的倍数，便于后续插入
            cursor.execute(
                """
            UPDATE vs_http_routes SET priority = %s WHERE id = %s
            """,
                (new_priority, route['id']),
            )

        self.conn.commit()
        print(f"已重新整理 {len(routes)} 条路由规则的优先级")

    def insert_route_at_position(self, vs_global_id: int, route_data: Dict[str, Any], position: int):
        """在指定位置插入路由规则

        Args:
            vs_global_id: VirtualService全局配置ID
            route_data: 路由规则数据
            position: 插入位置（1-based，1表示第一个位置）
        """
        cursor = self.conn.cursor(dictionary=True)

        # 获取当前所有路由规则
        cursor.execute(
            """
        SELECT id, priority FROM vs_http_routes WHERE vs_global_id = %s ORDER BY priority ASC, id ASC
        """,
            (vs_global_id,),
        )

        existing_routes = cursor.fetchall()

        if position <= 0:
            position = 1
        elif position > len(existing_routes) + 1:
            position = len(existing_routes) + 1

        # 计算新规则的优先级
        if position == 1:
            # 插入到第一个位置
            if existing_routes:
                new_priority = existing_routes[0]['priority'] - 5
            else:
                new_priority = 10
        elif position > len(existing_routes):
            # 插入到最后一个位置
            if existing_routes:
                new_priority = existing_routes[-1]['priority'] + 10
            else:
                new_priority = 10
        else:
            # 插入到中间位置
            prev_priority = existing_routes[position - 2]['priority']
            next_priority = existing_routes[position - 1]['priority']
            new_priority = (prev_priority + next_priority) // 2

            # 如果优先级相同，需要重新整理
            if new_priority == prev_priority or new_priority == next_priority:
                self.reorder_route_priorities(vs_global_id)
                # 重新计算优先级
                new_priority = (position - 1) * 10 + 5

        # 插入新路由规则
        cursor.execute(
            """
        INSERT INTO vs_http_routes 
        (vs_global_id, name, priority, match_rules, rewrite_rules, forward_type, forward_detail, timeout)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
        """,
            (
                vs_global_id,
                route_data.get('name'),
                new_priority,
                route_data.get('match_rules'),
                route_data.get('rewrite_rules'),
                route_data['forward_type'],
                route_data['forward_detail'],
                route_data.get('timeout'),
            ),
        )

        self.conn.commit()
        print(f"已在位置 {position} 插入新的路由规则，优先级: {new_priority}")
        return cursor.lastrowid

    def move_route_to_position(self, route_id: int, new_position: int):
        """将路由规则移动到指定位置

        Args:
            route_id: 路由规则ID
            new_position: 新位置（1-based）
        """
        cursor = self.conn.cursor(dictionary=True)

        # 获取要移动的路由规则
        cursor.execute(
            """
        SELECT vs_global_id, name, match_rules, rewrite_rules, forward_type, forward_detail, timeout
        FROM vs_http_routes WHERE id = %s
        """,
            (route_id,),
        )

        route = cursor.fetchone()
        if not route:
            print(f"未找到ID为 {route_id} 的路由规则")
            return False

        # 删除原路由规则
        cursor.execute("DELETE FROM vs_http_routes WHERE id = %s", (route_id,))

        # 重新插入到新位置
        route_data = {
            'name': route['name'],
            'match_rules': route['match_rules'],
            'rewrite_rules': route['rewrite_rules'],
            'forward_type': route['forward_type'],
            'forward_detail': route['forward_detail'],
            'timeout': route['timeout'],
        }

        self.insert_route_at_position(route['vs_global_id'], route_data, new_position)
        print(f"已将路由规则移动到位置 {new_position}")
        return True

    def get_routes_with_position(self, vs_global_id: int):
        """获取路由规则列表，包含位置信息"""
        cursor = self.conn.cursor(dictionary=True)

        # 先获取路由规则
        cursor.execute(
            """
        SELECT id, vs_global_id, name, priority, match_rules, rewrite_rules, forward_type, forward_detail, timeout, created_at, updated_at
        FROM vs_http_routes 
        WHERE vs_global_id = %s
        ORDER BY priority ASC, id ASC
        """,
            (vs_global_id,),
        )

        routes = cursor.fetchall()

        # 添加位置信息
        for index, route in enumerate(routes):
            route['position'] = index + 1

        return routes

    def generate_virtualservice_yaml(self, vs_name: str, namespace: str) -> Optional[str]:
        """根据数据库数据生成VirtualService YAML"""
        cursor = self.conn.cursor(dictionary=True)

        # 获取全局配置
        cursor.execute(
            """
        SELECT * FROM vs_global WHERE name = %s AND namespace = %s
        """,
            (vs_name, namespace),
        )

        global_config = cursor.fetchone()
        if not global_config:
            return None

        # 获取路由规则，按优先级排序
        cursor.execute(
            """
        SELECT * FROM vs_http_routes WHERE vs_global_id = %s ORDER BY priority ASC, id ASC
        """,
            (global_config['id'],),
        )

        routes = cursor.fetchall()

        # 构建VirtualService结构
        vs_config = {
            "apiVersion": "networking.istio.io/v1beta1",
            "kind": "VirtualService",
            "metadata": {"name": global_config['name'], "namespace": global_config['namespace']},
            "spec": {"hosts": json.loads(global_config['hosts'])},
        }

        # 添加gateways（如果有）
        if global_config['gateways']:
            vs_config['spec']['gateways'] = json.loads(global_config['gateways'])

        # 构建HTTP路由规则
        http_routes = []
        for route in routes:
            http_route = {}

            # 添加name（如果有）
            if route['name']:
                http_route['name'] = route['name']

            # 添加match规则
            if route['match_rules']:
                http_route['match'] = json.loads(route['match_rules'])

            # 添加rewrite规则
            if route['rewrite_rules']:
                http_route['rewrite'] = json.loads(route['rewrite_rules'])

            # 添加转发规则
            if route['forward_type'] == 'route':
                http_route['route'] = json.loads(route['forward_detail'])
            elif route['forward_type'] == 'delegate':
                http_route['delegate'] = json.loads(route['forward_detail'])

            # 添加timeout
            if route['timeout']:
                http_route['timeout'] = route['timeout']

            http_routes.append(http_route)

        # 添加默认路由（如果配置了）
        if global_config['df_forward_type'] and global_config['df_forward_detail']:
            default_route = {}

            # 默认路由没有match条件，直接添加转发规则
            if global_config['df_forward_type'] == 'route':
                default_route['route'] = json.loads(global_config['df_forward_detail'])
            elif global_config['df_forward_type'] == 'delegate':
                default_route['delegate'] = json.loads(global_config['df_forward_detail'])

            # 添加默认路由的timeout
            if global_config['df_forward_timeout']:
                default_route['timeout'] = global_config['df_forward_timeout']

            http_routes.append(default_route)

        vs_config['spec']['http'] = http_routes

        # 转换为YAML格式字符串
        import yaml

        return yaml.dump(vs_config, default_flow_style=False, allow_unicode=True)

    def add_k8s_cluster_relation(self, k8s_name: str, vs_id: int):
        """添加K8S集群与VirtualService的关联关系"""
        cursor = self.conn.cursor(dictionary=True)
        
        cursor.execute(
            """
        INSERT INTO k8s_cluster (k8s_name, vs_id)
        VALUES (%s, %s)
        ON DUPLICATE KEY UPDATE
            updated_at = CURRENT_TIMESTAMP
        """,
            (k8s_name, vs_id),
        )
        
        self.conn.commit()
        print(f"已添加K8S集群 '{k8s_name}' 与VirtualService ID {vs_id} 的关联关系")
        return cursor.lastrowid

    def remove_k8s_cluster_relation(self, k8s_name: str, vs_id: int):
        """删除K8S集群与VirtualService的关联关系"""
        cursor = self.conn.cursor(dictionary=True)
        
        cursor.execute(
            "DELETE FROM k8s_cluster WHERE k8s_name = %s AND vs_id = %s",
            (k8s_name, vs_id),
        )
        
        affected_rows = cursor.rowcount
        self.conn.commit()
        
        if affected_rows > 0:
            print(f"已删除K8S集群 '{k8s_name}' 与VirtualService ID {vs_id} 的关联关系")
        else:
            print(f"未找到K8S集群 '{k8s_name}' 与VirtualService ID {vs_id} 的关联关系")
        
        return affected_rows > 0

    def get_k8s_cluster_relations(self, k8s_name: Optional[str] = None, vs_id: Optional[int] = None):
        """获取K8S集群与VirtualService的关联关系
        
        Args:
            k8s_name: K8S集群名称，为None时查询所有集群
            vs_id: VirtualService ID，为None时查询所有VS
        """
        cursor = self.conn.cursor(dictionary=True)
        
        base_query = """
        SELECT 
            k.id,
            k.k8s_name,
            k.vs_id,
            v.name as vs_name,
            v.namespace as vs_namespace,
            k.updated_at
        FROM k8s_cluster k
        LEFT JOIN vs_global v ON k.vs_id = v.id
        """
        
        conditions = []
        params = []
        
        if k8s_name:
            conditions.append("k.k8s_name = %s")
            params.append(k8s_name)
        
        if vs_id:
            conditions.append("k.vs_id = %s")
            params.append(vs_id)
        
        if conditions:
            query = base_query + " WHERE " + " AND ".join(conditions)
        else:
            query = base_query
        
        query += " ORDER BY k.k8s_name, k.vs_id"
        
        cursor.execute(query, params)
        return cursor.fetchall()

    def get_vs_by_k8s_cluster(self, k8s_name: str):
        """根据K8S集群名称获取关联的所有VirtualService"""
        cursor = self.conn.cursor(dictionary=True)
        
        cursor.execute(
            """
        SELECT 
            v.id,
            v.name,
            v.namespace,
            v.gateways,
            v.hosts,
            v.protocol,
            v.df_forward_type,
            v.df_forward_detail,
            v.df_forward_timeout,
            v.created_at,
            v.updated_at,
            k.updated_at as relation_created_at,
            k.updated_at as relation_updated_at
        FROM vs_global v
        INNER JOIN k8s_cluster k ON v.id = k.vs_id
        WHERE k.k8s_name = %s
        ORDER BY v.name, v.namespace
        """,
            (k8s_name,),
        )
        
        return cursor.fetchall()

    def get_k8s_clusters_by_vs(self, vs_id: int):
        """根据VirtualService ID获取关联的所有K8S集群"""
        cursor = self.conn.cursor(dictionary=True)
        
        cursor.execute(
            """
        SELECT 
            k.id,
            k.k8s_name,
            k.updated_at,
            k.updated_at
        FROM k8s_cluster k
        WHERE k.vs_id = %s
        ORDER BY k.k8s_name
        """,
            (vs_id,),
        )
        
        return cursor.fetchall()


def main():
    """主函数"""
    print("正在初始化Istio VirtualService数据库...")

    # 优先从.env文件读取数据库连接参数，失败则从utils模块读取
    try:
        from dotenv import load_dotenv
        import os
        
        # 尝试加载.env文件
        env_path = os.path.join(os.path.dirname(__file__), '.env')
        load_dotenv(env_path)
        
        DB_HOST = os.environ.get('DB_HOST')
        DB_PORT = os.environ.get('DB_PORT')
        DB_USER = os.environ.get('DB_USER')
        DB_PASSWORD = os.environ.get('DB_PASSWORD')
        DB_NAME = os.environ.get('DB_NAME')
        
        # 如果.env文件中没有配置或配置为空，则从utils模块读取
        if not all([DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME]):
            raise ImportError("Environment variables not found in .env")
            
        print("使用.env文件中的数据库配置")
        
    except (ImportError, FileNotFoundError):
        # 如果.env读取失败，从utils模块导入
        try:
            import sys
            import os
            sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
            from utils import DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME
            print("使用utils模块中的数据库配置")
        except ImportError:
            # 如果都失败，使用默认值
            DB_HOST = "localhost"
            DB_PORT = 3306
            DB_USER = "root"
            DB_PASSWORD = "123456"
            DB_NAME = "istio_route"
            print("使用默认数据库配置")   

    db_host = DB_HOST
    db_port = int(DB_PORT or '3306')
    db_user = DB_USER
    db_password = DB_PASSWORD
    db_name = DB_NAME

    print(f"连接到 MySQL 数据库: {db_user}@{db_host}:{db_port}/{db_name}")

    db = VirtualServiceDB(host=db_host, port=db_port, user=db_user, password=db_password, database=db_name)
    try:
        db.connect()
        db.init_tables()

        # 询问是否插入示例数据
        response = input("是否插入示例数据？(y/n): ")
        if response.lower() in ['y', 'yes', '是']:
            db.insert_sample_data()

            # 演示路由规则位置管理功能
            print("\n=== 演示路由规则位置管理功能 ===")

            # 获取VirtualService ID
            cursor = db.conn.cursor(dictionary=True)
            cursor.execute("SELECT id FROM vs_global WHERE name = %s", ('example-vs',))
            result = cursor.fetchone()
            vs_id = result['id']

            # 显示当前路由规则
            print("\n当前路由规则顺序:")
            routes = db.get_routes_with_position(vs_id)
            for route in routes:
                print(f"  位置 {route['position']}: {route['name']} (优先级: {route['priority']})")

            # 演示插入新规则到指定位置
            print("\n演示: 在位置2插入新的路由规则...")
            new_route_data = {
                'name': 'new-middleware-route',
                'match_rules': json.dumps([{"uri": {"prefix": "/middleware"}}]),
                'rewrite_rules': None,
                'forward_type': 'route',
                'forward_detail': json.dumps(
                    [{'destination': {'host': 'middleware-service', 'port': {'number': 8080}}}]
                ),
                'timeout': '15s',
            }

            db.insert_route_at_position(vs_id, new_route_data, 2)

            # 显示插入后的路由规则
            print("\n插入后的路由规则顺序:")
            routes = db.get_routes_with_position(vs_id)
            for route in routes:
                print(f"  位置 {route['position']}: {route['name']} (优先级: {route['priority']})")

            # 演示移动路由规则
            print("\n演示: 将第3个路由规则移动到第1个位置...")
            if len(routes) >= 3:
                third_route_id = routes[2]['id']
                db.move_route_to_position(third_route_id, 1)

                # 显示移动后的路由规则
                print("\n移动后的路由规则顺序:")
                routes = db.get_routes_with_position(vs_id)
                for route in routes:
                    print(f"  位置 {route['position']}: {route['name']} (优先级: {route['priority']})")

            # 生成最终的YAML
            yaml_content = db.generate_virtualservice_yaml("example-vs", "default")
            if yaml_content:
                print("\n最终生成的VirtualService YAML:")
                print("=" * 50)
                print(yaml_content)
                print("=" * 50)

            # 演示K8S集群关联功能
            print("\n=== 演示K8S集群关联功能 ===")
            
            # 显示所有K8S集群关联关系
            print("\n所有K8S集群关联关系:")
            relations = db.get_k8s_cluster_relations()
            for relation in relations:
                print(f"  集群: {relation['k8s_name']} -> VS: {relation['vs_name']}({relation['vs_namespace']}) [ID: {relation['vs_id']}]")
            
            # 根据K8S集群查询VirtualService
            print("\n查询K8S1集群关联的VirtualService:")
            k8s1_vs_list = db.get_vs_by_k8s_cluster("K8S1")
            for vs in k8s1_vs_list:
                print(f"  VS: {vs['name']}({vs['namespace']}) - 关联更新时间: {vs['relation_updated_at']}")
            
            # 根据VirtualService查询K8S集群
            print(f"\n查询VirtualService ID {vs_id} 关联的K8S集群:")
            vs_k8s_list = db.get_k8s_clusters_by_vs(vs_id)
            for k8s in vs_k8s_list:
                print(f"  集群: {k8s['k8s_name']} - 关联时间: {k8s['updated_at']}")
            
            # 演示添加新的K8S集群关联
            print("\n演示: 添加新的K8S集群关联 (K8S3 -> example-vs)...")
            db.add_k8s_cluster_relation("K8S3", vs_id)
            
            # 显示更新后的关联关系
            print("\n更新后的K8S集群关联关系:")
            relations = db.get_k8s_cluster_relations()
            for relation in relations:
                print(f"  集群: {relation['k8s_name']} -> VS: {relation['vs_name']}({relation['vs_namespace']}) [ID: {relation['vs_id']}]")

        print("\n数据库初始化完成！")
        print(f"数据库连接: {db.user}@{db.host}:{db.port}/{db.database}")
        print("\n支持的功能:")
        print("  路由规则管理:")
        print("    - insert_route_at_position(): 在指定位置插入路由规则")
        print("    - move_route_to_position(): 移动路由规则到指定位置")
        print("    - reorder_route_priorities(): 重新整理优先级")
        print("    - get_routes_with_position(): 获取带位置信息的路由规则列表")
        print("  K8S集群关联管理:")
        print("    - add_k8s_cluster_relation(): 添加K8S集群与VS的关联关系")
        print("    - remove_k8s_cluster_relation(): 删除K8S集群与VS的关联关系")
        print("    - get_k8s_cluster_relations(): 获取K8S集群与VS的关联关系")
        print("    - get_vs_by_k8s_cluster(): 根据K8S集群获取关联的VS")
        print("    - get_k8s_clusters_by_vs(): 根据VS获取关联的K8S集群")

    except Exception as e:
        import traceback
        print(f"初始化失败: {type(e).__name__}: {e}")
        print("详细错误信息:")
        traceback.print_exc()
    finally:
        db.close()


if __name__ == "__main__":
    main()
